package com.sunday.authorization.security.authentication;

import com.sunday.common.core.enums.ErrorCodeEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.security.core.AuthenticationException;

import java.util.Optional;

/**
 * 通用自定义异常
 *
 * @author sunday
 * @since 2024/9/16
 */
@Slf4j
public class CustomAuthenticationException extends AuthenticationException {

    @Getter
    private String code;

    public CustomAuthenticationException(ErrorCodeEnum errorCodeEnum) {
        this(errorCodeEnum.errorCode, errorCodeEnum.errorMessage);
    }

    public CustomAuthenticationException(String code, String message) {
        super(message);
        this.code = code;
    }

    /**
     * 默认开启替换
     *
     * @param errorCodeEnum
     * @param message
     */
    public CustomAuthenticationException(ErrorCodeEnum errorCodeEnum, @Nullable String message) {
        this(errorCodeEnum, message, false);
    }

    /**
     * 查看传入的错误信息是否存在，并且判定是追加消息还是替换
     *
     * @param errorCodeEnum
     * @param message
     * @param isAppend
     */
    public CustomAuthenticationException(ErrorCodeEnum errorCodeEnum, @Nullable String message, boolean isAppend) {
        this(errorCodeEnum.errorCode, errorCodeEnum.errorMessage, message, isAppend);
    }

    public CustomAuthenticationException(String errorCode, String errorMessage, @Nullable String message, boolean isAppend) {
        super(Optional.ofNullable(message)
                .filter(StringUtils::isNotBlank)
                .map(m -> isAppend ? STR."\{errorMessage}(\{m})" : m)
                .orElse(errorMessage));
        this.code = errorCode;
    }

    @Override
    public String toString() {
        return STR."\{getClass().getName()}:(\{getCode()}=\{getLocalizedMessage()})";
    }


}
